package com.skyworthclub.competition.config.security;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.skyworthclub.competition.beans.Role;
import com.skyworthclub.competition.beans.User;
import com.skyworthclub.competition.service.RoleService;
import com.skyworthclub.competition.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author li
 * @version 1.0
 * @since 18-10-15 下午8:22
 * 自定义用户信息来源（从数据库获取）
 **/
@Component
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;
    private final RoleService roleService;

    @Autowired
    public CustomUserDetailsServiceImpl(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名获取用户信息
        User user = userService.getUserInfo(username);
        //用户不存在，抛出异常
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        //简单分配权限
        Set<GrantedAuthority> authorities = grantAuthority(user.getId());
        //构建UserDetails返回
        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(), authorities);
    }


    private Set<GrantedAuthority> grantAuthority(Integer userId) {
        Set<GrantedAuthority> authorities = new HashSet<>();
        List<Role> roles = roleService.getRolesByUserId(userId);
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        authorities.add(new SimpleGrantedAuthority("user"));
        return authorities;
    }
}
